﻿//==================================================================
// Copyright (C) 2011 深圳市中旭企业管理股份有限公司
// 文件名: Index.cs
// 作 者：
// 日 期：2011/09/16
// 描 述：主页面管理类
// 版 本：2.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 2.00   2011-10-27   hexingxiang 
// 2.01   2012-03-22   曾洋              规范代码
//==================================================================
using System;
using System.Data;
using System.Collections;
using System.Web;
using ZX.EHR.Library;
using System.Configuration;
using System.Web.Security;
using log4net;
using ZX.AspNetComet.Core;
//using Server.Channels;

namespace ZX.WebApp
{
    public partial class Index : ZX.Web.UI.Controls.BasePage
    {
        /// <summary>
        /// 从KM系统登录的账号
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            try
            {
                string UserID = Request["UserID"];
                if (string.IsNullOrEmpty(UserID) == false)
                {
                    UserID = ZX.KM.Core.Common.SecurityUtility.Decrypt(UserID, web_url_key);
                    DatUser u = new DatUser
                    {
                        UserID = new Guid(UserID)
                    };

                    ZX.BLL.BUser b = new BLL.BUser();
                    Session["User"] = b.GetDatUserByLoginName(u);
                    Session["IsOutSite"] = false;
                }
            }
            catch (Exception ex)
            {
                var logger = LogManager.GetLogger(GetType());
                logger.Error(ex.Message, ex);
            }
            base.OnInit(e);
           
        }

        /// <summary>
        /// 待拼接的流程树
        /// </summary>
        public string workFlowTree { get; set; }
        protected ArrayList classIdItem = new ArrayList();  //存放WFClassId字段值
        protected void Page_Load(object sender, EventArgs e)
        {
            
            //Response.Buffer = true;
            //Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            //Response.Expires = 0;
            //Response.CacheControl = "no-cache";
            
            //注册
            CometStateManager.RegisterAspNetCometScripts(this);
            //---------------------------------------------------
            if ((this.UserId) == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                this.labUserName.Text = this.User.UName;
                //配置是否显示业务流程菜单
                if (System.Configuration.ConfigurationManager.AppSettings["workflow"] == null ? false : System.Configuration.ConfigurationManager.AppSettings["workflow"].ToString() == "show")
                {
                    InitData();
                }
            }
            

        }
        /// <summary>
        /// 初始化左边的日常业务
        /// </summary>
        private void InitData()
        {
            //if()
            //{

            //}
          
            //调用流程服务接口实例
            CrmWorkFlowService.WorkFlowServiceClient workFlowServiceClient = new CrmWorkFlowService.WorkFlowServiceClient();
            //获取该用户拥有的所有流程
            DataTable dt = workFlowServiceClient.GetAllowsStartWorkFlows(this.User.LoginName);
            DataTable dts = workFlowServiceClient.SetHFWorkFlowClass(); //获取流程类层级
            ArrayList listItem = new ArrayList(); //
           
            string nowcllevel = "1";
            string filter = string.Empty;
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (var item in dt.Select("classlevel= '2'"))
                {
                    if (dt.Select("classlevel= '1' and WFClassId = '" + item["FatherId"].ToString() +"'").Length == 0)
                    {
                        foreach (var items in dts.Select("WFClassId = '" + item["FatherId"].ToString() +"'"))
                        {
                            if (listItem.IndexOf(items["WFClassId"].ToString()) == -1)
                            {
                                listItem.Add(items["WFClassId"].ToString());
                                dt.Rows.Add(items["WFClassId"].ToString(), items["Caption"].ToString(),items["FatherId"].ToString(), Guid.NewGuid(), "", "", "", items["ClassLevel"].ToString(), "", "");
                            }
                        }
                    }
                }
                workFlowTree = "<div title=\"日常流程\" style=\"padding:0px\"><ul class=\"easyui-tree\" id=\"leftTree\">";
                foreach (DataRow dr in dt.Rows)
                {
                    nowcllevel = dr["classlevel"].ToString();
                    if (nowcllevel == "1")
                    {
                        if (classIdItem.IndexOf(nowcllevel) == -1)
                        {
                            classIdItem.Add(nowcllevel);
                            LoadWorkflowClass(dt, nowcllevel);
                            break;//避免多次循环
                        }
                    }
                }
               
                workFlowTree += "</ul></div>";
            }
           
        }
        /// <summary>
        /// 递归装载流程分类
        /// </summary>
        /// <param name="key"></param>
        /// <param name="startNodes"></param>
        public void LoadWorkflowClass(DataTable dt, string key)
        {
           
            string filter = "";
            try
            {
                filter = "classlevel='" + key + "'";
                DataView dv = new DataView(dt);
                dv.RowFilter = filter;
                foreach (DataRowView row in dv)
                {
                    string nowClassId = row["WFClassId"].ToString();
                    if (classIdItem.IndexOf(nowClassId) == -1)
                    {
                        classIdItem.Add(nowClassId);
                        workFlowTree += "<li state=\"closed\" ><span >" + row["Caption"].ToString() + "</span><ul>";
                        LoadWorkflow(dt, row["WFClassId"].ToString());
                        loadChildClass(dt, row["WFClassId"].ToString());//递归加载子分类
                        workFlowTree += "</ul></li>";
                    }
                }
                
            }
            catch (Exception ex)
            {
                 throw new Exception("LoadWorkflowClass函数," + filter + ex.Message);
            }
        }
        /// <summary>
        /// 加载流程
        /// </summary>
        /// <param name="key"></param>
        /// <param name="startNodes"></param>
        public void LoadWorkflow(DataTable dt, string key)
        {
            string filter = "";
            filter = "WFClassId='" + key + "' and WorkTaskid <> ''";
            DataView dv = new DataView(dt);
            dv.RowFilter = filter;
            try
            {
                foreach (DataRowView row in dv)
                {
                    if (row["WFClassId"].ToString() == key)
                    {
                        string nowflowid = row["workflowId"].ToString();
                        if (classIdItem.IndexOf(row["workflowId"].ToString()) == -1)
                        {
                            classIdItem.Add(nowflowid);
                            workFlowTree += "<li state=\"closed\"><span>" + row["FlowCaption"].ToString() + "</span>";
                            LoadStartTask(dt, row["workflowId"].ToString());
                            workFlowTree += "</li>";
                        }
                    }
                }

            }
            catch (Exception ex)
            {

                throw new Exception("LoadWorkflow函数," + ex.Message);
            }
        }
        public void loadChildClass(DataTable dt, string key)
        {
            string filter = "";
            try
            {
                filter = "FatherId='" + key + "'";
                DataView dv = new DataView(dt);
                dv.RowFilter = filter;
                foreach (DataRowView row in dv)
                {
                    string nowClassId = row["WFClassId"].ToString();
                    if (classIdItem.IndexOf(nowClassId) == -1)
                    {
                        classIdItem.Add(nowClassId);
                        workFlowTree += "<li state=\"closed\" ><span >" + row["Caption"].ToString() + "</span><ul>";
                        LoadWorkflow(dt, row["WFClassId"].ToString());
                        loadChildClass(dt, row["WFClassId"].ToString());
                        workFlowTree += "</ul></li>";
                    }

                }
              
            }
            catch (Exception ex)
            {

                throw new Exception("loadChildClass函数," + filter + ex.Message);
            }
        }
        /// <summary>
        /// 加载启动节点
        /// </summary>
        /// <param name="key"></param>
        /// <param name="startNodes"></param>
        public void LoadStartTask(DataTable dt, string key)
        {
            string filter = "";
            string tmpTaskId = "";
            filter = "workflowId='" + key + "'";
            tmpTaskId = "###";
            DataView dv = new DataView(dt);
            dv.RowFilter = filter;
            try
            {
                foreach (DataRowView row in dv)
                {
                    string nowtaskid = row["WorktaskId"].ToString();
                    if (classIdItem.Count > 0)
                    {
                        foreach (var item in classIdItem)
                        {
                            if (item == nowtaskid)
                                continue;//避免重复添加
                        }
                    }
                    classIdItem.Add(nowtaskid);
                    tmpTaskId = nowtaskid;
                    string workflowId = row["WorkFlowId"].ToString();

                    workFlowTree += "<ul><li><span ><a onclick=\"addTabs('" + row["TaskCaption"].ToString() + "','crm/BasePages/StartWorkflow.aspx?title=" + row["TaskCaption"].ToString() + "&WorkflowId=" + row["WorkflowId"].ToString() + "&WorktaskId=" + row["WorktaskId"].ToString() + "')\">" + row["TaskCaption"].ToString() + "</a></span></li></ul>";
                }
               
            }
            catch (Exception ex)
            {

                throw new Exception("LoadStartTask函数," + ex.Message);
            }
        }
    }
}
